import re
import time
import pymongo
import constant as c
import common.gyblog as log
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

LOG = log.get_logger()
SERVICE = ChromeService(executable_path="../common/chromedriver.exe")


# 查询是否在数据库中，没有则插入
def check_in_db(tor, keyword):
    # 连接数据库
    db_client = pymongo.MongoClient(c.CONNECTION_STR)
    db_database = db_client[c.DATA_BASE]
    db_col = db_database['comic_download_record']

    query = {'tor': tor}
    query_ans = list(db_col.find(query))

    if len(query_ans) == 0:
        # 记录到数据库
        current_date = time.strftime("%Y-%m-%d", time.localtime())
        my_dict = {'tor': tor, 'keyword': keyword}
        db_col.insert_one(my_dict)
    elif len(query_ans) == 1:
        print('{}已存在'.format(tor))
    else:
        print('数据重复')

    db_client.close()


def download_sukebei_by_keyword(keyword):
    for i in range(1, 15):
        url = 'https://sukebei.nyaa.si/?f=2&c=0_0&q={}&p={}'.format(keyword, str(i))
        # 创建 WebDriver 对象
        driver = webdriver.Chrome(service=SERVICE)
        driver.get(url)
        # 使用 XPath 定位元素
        elements = driver.page_source
        tors = re.findall("magnet:\?xt=urn:.*?&amp", elements)

        if len(tors) == 0:
            print('{}：没有找到tor'.format(url))
            LOG.info('{}：没有找到tor'.format(url))
        else:
            print('{}：查询到{}个'.format(url, len(tors)))
            LOG.info('{}：查询到{}个'.format(url, len(tors)))
            for tor in tors:
                check_in_db(tor, keyword)
                print(tor)
                LOG.info(tor)
        driver.close()


def query_by_keyword(keyword):
    # 连接数据库
    db_client = pymongo.MongoClient(c.CONNECTION_STR)
    db_database = db_client[c.DATA_BASE]
    db_col = db_database['comic_download_record']

    query = {'keyword': keyword}
    query_ans = list(db_col.find(query))

    len_query = len(query_ans)

    if len_query == 0:
        print('没有查询到{}'.format(keyword))
    else:
        for q in query_ans:
            print(q['tor'])
    print('关键词：{}，查询到{}个'.format(keyword, len_query))
    db_client.close()


if __name__ == '__main__':
    keyword = 'C98'
    download_sukebei_by_keyword(keyword)
    # query_by_keyword(keyword)
